const aedes = require('aedes')
const net = require('net')
const fs = require('fs')
const options = {
    key: fs.readFileSync('/etc/nginx/iot.hsesmartinc.com.key'),
    cert: fs.readFileSync('/etc/nginx/iot.hsesmartinc.com.pem'),
    // 如果需要客户端认证
    // requestCert: true,
    // rejectUnauthorized: false
};
const httpServer = require('https').createServer(options)
const ws = require('websocket-stream')
const {log,logI,logE} = require('./log.js')

const port = 1883
const wsPort = 3100

const aedesApp = new aedes({
    heartbeatInterval: 60000,
    connectTimeout: 120000,
})

const server = net.createServer(aedesApp.handle)

server.listen(port, function() {
    log.info('server listening on port', port)
})

// 支持浏览器连接 - 将mqtt与http服务关联
// mqtt不能直接支持浏览器连接，需要借助websocket支持
ws.createServer({
    server: httpServer
}, aedesApp.handle)

httpServer.listen(wsPort, function() {
    log.info('websocket server listening on port', wsPort)
})

aedesApp.on('clientError', function(client, err) {
    logE("S-A", client.id, "mqtt-clientError", `${JSON.stringify(err.message)}`, "null")
})

aedesApp.on('connectionError', function(client, err) {
    logE("S-A", client.id, "mqtt-connectionError", `${JSON.stringify(err.message)}`, "null")
})

aedesApp.on('publish', function(packet, client) {
    if (client) {
        log.info('message from client', client.id)
        let topic = packet.topic;
        switch (topic) {
            case 'gateway-web':
                logI("C-S", packet.topic, "gateway-web", `${packet.payload.toString()}`, "null")
                break;
            default:
                break;
        }
    }
})

aedesApp.on('client', function(client) {
    log.info('new client', client.id);

})